/**
 * @brief EEPROM driver implementation
 * @author Gilad Avidov
 */
#include <mcs51reg.h>
#include <stdio.h>
#include "i2c.h"
#include "eeprom.h"

#define EEPROM_ADDR        (0xA)

unsigned char eeprom_read(unsigned char block, unsigned char offset,
                            xdata unsigned char *buf, unsigned char len)
{
    unsigned seven_bit_addr = (EEPROM_ADDR << 3) | (block & 0x7);
    if (i2c_send_address(seven_bit_addr, I2C_WR))
    {
        printf("eeprom_read(block:%d) faild on i2c_send_address(0x%X, WR)\n\r",
               block, seven_bit_addr);
        return 1;
    }

    if (i2c_send_byte(offset))
    {
        printf("eeprom_read(block:%d offset:%d) i2c_send_byte(0x%X)\n\r",
               block, offset, offset);
        return 1;
    }

    if (i2c_send_address(seven_bit_addr, I2C_RD))
    {
        printf("eeprom_read(block:%d) faild on i2c_send_address(0x%X, RD)\n\r",
               block, seven_bit_addr);
        return 1;
    }

    for ( ; len ; --len, ++buf)
        i2c_recv_byte(buf, len == 1);

    i2c_stop();

    return 0;
}

unsigned char eeprom_write(unsigned char block, unsigned char offset,
                            xdata unsigned char *buf, unsigned char len)
{
    unsigned seven_bit_addr = (EEPROM_ADDR << 3) | (block & 0x7);
    if (i2c_send_address(seven_bit_addr, I2C_WR))
    {
        printf("error: eeprom_write(block:%d) faild on i2c_send_address(0x%X, WR)\n\r",
               block, seven_bit_addr);
        return 1;
    }

    if (i2c_send_byte(offset))
    {
        printf("error: eeprom_write(block:%d offset:%d) i2c_send_byte(0x%X)\n\r",
               block, offset, offset);
        return 1;
    }

    for ( ; len ; --len, ++buf)
        if (i2c_send_byte(*buf)){
            printf("error: eeprom_write(block:%d offset:%d) i2c_send_byte(0x%X)\n\r",
                   block, offset, *buf);
            return 1;
        };

    i2c_stop();

    return 0;
}

void eereset()
{
    i2c_reset();
}
